package com.shenhaofeng.app.loader.content;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;

import java.security.InvalidParameterException;


/**
 * 内容加载器，一般情况下实在加载页面数据时使用，例如一个item的详细页面.其功能通过不同的Config来实现
 * Created by Administrator on 2016/9/7.
 */
public class ContentLoader<R> {

    private static final String TAG = "ContentLoader";

    private View mStatusView;

    private View mContentView;

    private Component<R> mComponent;

    private ContentSource<R> mContentSource;

    private OnBindContentListener<R> mOnBindContentListener;

    private boolean isAttached = false;


    /**
     * {@link Component}是必须了，它作为不同View协同合作的桥梁
     *
     * @param component
     */
    public ContentLoader(@NonNull Component<R> component) {
        this.mComponent = component;
    }


    /**
     * @param statusView
     * @param contentView
     */
    public void attach(@NonNull View statusView, @NonNull View contentView, @NonNull ContentSource<R> contentSource, @NonNull OnBindContentListener<R> onBindContentListener) {
        isAttached = true;
        this.mStatusView = statusView;
        this.mContentView = contentView;
        this.mContentSource = contentSource;
        this.mOnBindContentListener = onBindContentListener;
        boolean status = mComponent.hasContentView(mStatusView, mContentView);
        if (!status) {
            throw new InvalidParameterException("statusView和contentView不符合Config中限定的View条件");
        }
    }


    /**
     * 加载数据
     * @param args
     */
    public void load(@Nullable Bundle args) {
        if (!isAttached) {
            throw new IllegalStateException("在加载数据前必须要调用attach绑定视图");
        }
        mComponent.onPreLoad(mStatusView, mContentView);
        //首次加载
        mComponent.onLoad(mStatusView, mContentView, args, mOnBindContentListener, mContentSource);
    }

    /**
     * 调用这个方法，将会启动数据加载流程
     */
    public void load() {
        load(null);
    }


}
